<template>
	<el-card shadow="hover">
		<el-row class="flex mt15 mb20">
			<div class="flex-end">
				<el-button size="default" type="primary" @click="editPFOInstance">{{ state.tableData.editDesc
					}}</el-button>
			</div>
		</el-row>
		<el-form ref="tableRulesRef" :model="state.tableData" size="default">
			<el-table :data="state.tableData.data" border class="module-table-uncollected">
				<el-table-column v-for="item in state.tableData.header" show-overflow-tooltip :prop="item.prop"
					width="100px;" :label="item.label">
					<template v-slot:header>
						<span class="pl5">{{ item.label }}{{ item.unitCode }}</span>
					</template>
					<template v-slot="scope">
						<el-form-item :prop="`data.${scope.$index}.${item.prop}`">
							<div v-if="item.type === 'input'">
								<el-input v-model="scope.row[item.prop]" />
							</div>
							<div v-else-if="item.type === 'text'">
								<p>{{ scope.row[item.prop] }}</p>
							</div>
							<div v-else-if="item.type === 'button'">
								<el-button size="small" text type="primary"
									@click="removePFOInstance(scope.row)">删除</el-button>
							</div>
						</el-form-item>
					</template>
				</el-table-column>
			</el-table>
		</el-form>
		<el-row class="flex mt15" v-if="state.tableData.edit">
			<div class="flex-margin">
				<el-button size="default" type="primary" @click="selectProduct()">选择产品</el-button>
				<el-button size="default" type="success" @click="savePFOInstances(tableRulesRef)">保存</el-button>
			</div>
		</el-row>
	</el-card>
	<SelectProductDialog ref="selectProductDialogRef" @selectInstance="selectInstanceFromProduct" />
</template>

<script setup lang="ts" name="placeFollowOrderInstance">
import { reactive, ref, onBeforeMount, defineAsyncComponent } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useRoute } from 'vue-router';
import { usePFOInstanceApi } from '/@/api/order/placeFollowOrderInstance';
import { usePlaceFollowOrderApi } from '/@/api/order/placeFollowOrder';

// 获取路由数据
const route = useRoute();

// 引入组件
const SelectProductDialog = defineAsyncComponent(() => import('/@/views/order/placeFollowOrder/component/selectProductDialog.vue'));

// 引入 api 请求接口
const pFOInstanceApi = usePFOInstanceApi();
const placeFollowOrderApi = usePlaceFollowOrderApi();

// 打开新增菜单弹窗
const selectProduct = () => {
	selectProductDialogRef.value.openDialog(state.tableData.placeFollowOrderInfo?.id,
		state.tableData.placeFollowOrderInfo?.vendorId,
		state.tableData.placeFollowOrderInfo?.vendorProductTypeId,
		state.tableData.placeFollowOrderInfo?.vendorName,
		state.tableData.placeFollowOrderInfo?.vendorProductTypeName
	);
};

// 打开编辑页面
const editPFOInstance = () => {
	if (!state.tableData.edit) {
		state.tableData.edit = true;
		state.tableData.editDesc = '返回';
		const operate = { prop: 'operate', label: '操作', isRequired: false, type: 'button' };
		state.tableData.header.push(operate);
		for (const headerItem of state.tableData.header) {
			if (headerItem.type == 'text' && headerItem.isRequired) {
				headerItem.type = 'input';
			}
		}
	} else {
		state.tableData.edit = false;
		state.tableData.editDesc = '编辑';
		state.tableData.header = state.tableData.header.filter(header => header.prop !== 'operate');
		for (const headerItem of state.tableData.header) {
			if (headerItem.type == 'input') {
				headerItem.type = 'text';
			}
		}
	}
}

// 定义变量内容
const tableRulesRef = ref<FormInstance>();
const selectProductDialogRef = ref()
const state = reactive<PlaceFollowOrderInstanceState>({
	tableData: {
		data: [],
		header: [
			{ prop: 'productName', label: '产品名称', isRequired: false, type: 'text' },
			{ prop: 'variantCodeOneValueWithDesc', label: '变体1', isRequired: false, type: 'text' },
			{ prop: 'variantCodeTwoValueWithDesc', label: '变体2', isRequired: false, type: 'text' },
			{ prop: 'productLength', label: '产品-长', isRequired: false, type: 'text', unitCode: 'CM' },
			{ prop: 'productWidth', label: '产品-宽', isRequired: false, type: 'text', unitCode: 'CM' },
			{ prop: 'productHeight', label: '产品-高', isRequired: false, type: 'text', unitCode: 'CM' },
			{ prop: 'outerCartonPackCount', label: '装箱量', isRequired: false, type: 'text' },
			{ prop: 'packetLength', label: '装箱-长', isRequired: false, type: 'text', unitCode: 'CM' },
			{ prop: 'packetWidth', label: '装箱-宽', isRequired: false, type: 'text', unitCode: 'CM' },
			{ prop: 'packetHeight', label: '装箱-高', isRequired: false, type: 'text', unitCode: 'CM' },
			{ prop: 'packetTrueWeight', label: '单箱重量', isRequired: false, type: 'text', unitCode: 'KG' },
			{ prop: 'asin', label: 'asin', isRequired: true, type: 'text' },
			{ prop: 'sku', label: 'SKU', isRequired: true, type: 'text' },
			{ prop: 'price', label: '售价', isRequired: true, type: 'text' },
			{ prop: 'declarePrice', label: '链接申报售价', isRequired: true, type: 'text' },
			{ prop: 'boxNumber', label: '箱数', isRequired: true, type: 'text' },
			{ prop: 'purchasePrice', label: '采购价', isRequired: true, type: 'text' },
			{ prop: 'payableShippingCostTotal', label: '应付运费-总', isRequired: false, type: 'text' },
			{ prop: 'payableShippingCost', label: '应付运费-单件', isRequired: false, type: 'text' },
			{ prop: 'payableTaxTotal', label: '应付税金-总', isRequired: false, type: 'text' },
			{ prop: 'payableTax', label: '应付税金-单件', isRequired: false, type: 'text' },
			{ prop: 'otherCost', label: '其他费用', isRequired: true, type: 'text' },
		],
		edit: false,
		editDesc: '编辑'
	},
});

//获取项目核算细节信息
async function initPFOInstanceData() {
	const param = {
		placeFollowOrderId: route.query.id,
	}
	const result = await pFOInstanceApi.queryPFOInstanceList(param);
	if (result.data == null)
		return Promise.resolve(true);
	const placeFollowOrderInstanceList: PlaceFollowOrderInstance[] = result.data.rows;
	state.tableData.data = [];
	for (const instance of placeFollowOrderInstanceList) {
		state.tableData.data.push(instance);
	}
	state.tableData.edit = false;
}

// 初始化工厂下单跟单记录
async function initPFOData() {
	const param = {
		id: route.query.id,
	}
	const result = await placeFollowOrderApi.placeFollowOrderDetail(param);
	if (result.data == null) {
		return Promise.resolve(true);
	}
	const placeFollowOrderDetail: PlaceFollowOrder = result.data;
	state.tableData.placeFollowOrderInfo = placeFollowOrderDetail;
}

// 保存
async function savePFOInstances(formEl: FormInstance | undefined) {
	if (state.tableData.data.length <= 0) return ElMessage.warning('工厂下单跟单细则为空');
	if (!formEl) return;
	const param = {
		placeFollowOrderId: route.query.id,
		instanceList: state.tableData.data,
	}
	await pFOInstanceApi.savePFOInstance(param);

	editPFOInstance();
	initPFOInstanceData();
};

// 删除
async function removePFOInstance(row: any) {
	const param = {
		id: row.id,
	}
	await pFOInstanceApi.deletePFOInstance(param);
	state.tableData.data = state.tableData.data.filter(item => item.id != row.id);
}

//添加一行
const selectInstanceFromProduct = (instanceList: []) => {
	if (instanceList.length > 0) {
		instanceList.forEach(item => {
			state.tableData.data.push(item);
		});
	}
}

// 页面加载前
onBeforeMount(() => {
	initPFOData();
	initPFOInstanceData();
});
</script>

<style scoped>
.flex-end {
	margin-left: auto;
}
</style>
